Ext.onReady(function(){
   
    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';
    var pagesize = 22;	
    var gridisedit = false;
    var openUrl = basePath
    + 'JarpListener?className=cn.com.jsepc.rep.report.FillDataDAO';
    openUrl += '&methodName=getDataGrid&paramCount=5&param_2='+repid+'&param_3='+corpid+'&param_4='+getDemlist(); 

    var modalwin_f = new Ext.Window({
        id:'modalwin_f',
        title:"维度信息",
        border:false,
        bodyBorder:false,
        layout:'fit',
        width:435,
        height:510,
        closeAction:'hide',
        //	    plain: true,
        modal: true,
        tbar:['-',{
            text: ' 确定 ',
            handler: function(){
                selectItem();
                modalwin_f.hide();
            }
        },'-',{
            text: ' 关闭 ',
            handler: function(){
                modalwin_f.hide();
            }
        },'-'],
        items:[p_wdxx]
    });
    
    var shuju_win = new Ext.Window({  //导出数据采集模板页面
        id:'shuju_win',
        title:"导出数据采集模板",
        border:false,
        bodyBorder:false,
       // layout:'fit',
        width:435,
        height:510,
        closeAction:'hide',
        modal: true,
        tbar:['-',{
            text: ' 确定 ',
            handler: function(){
                selectItem_shuju();
        	getExportDemlist();
                shuju_win.hide();
            }
        },'-',{
            text: ' 关闭 ',
            handler: function(){
        	shuju_win.hide();
            }
        },'-'],
        items:[shuju_weidu,shuju_pal]
    });
    var store = new Ext.data.Store({    
        proxy : new Ext.data.HttpProxy( {
            url : openUrl
        }),	       
        reader : jReader1
    });    
    var sm = new Ext.grid.RowSelectionModel({
        singleSelect : true
    });    
    cm.defaultSortable = true;
    var grid = new Ext.grid.EditorGridPanel({
        id:'grid_t',
        // region : 'center',
        anchor:'100% 95%',
		
        // renderTo:'qrgridDiv',
        store:store,
        //sm:sm,  
        cm:cm,  
        viewConfig : {
            forceFit : true
        },
        frame : true,
      //  loadMask:true,//数据加载时的遮罩功能 
        stripeRows: true, //显示行的分隔符
        columnLines : true,
        clicksToEdit: 1,
        autoScroll:true, //控制滚动条
        height:screen.height-400,
        stateful : true,
        stateId : 'grid_t',
        bbar : new Ext.PagingToolbar({
            pageSize: pagesize,
            store: store,
            paramNames : {
                start : 'param_0',
                limit : 'param_1'
            },
            displayInfo: true,
            emptyMsg : '没有数据需要显示&nbsp;&nbsp;'
        })
    }); 
    
    /* store.load({params : {
                param_0:0,
                param_1:pagesize
            }});
     */
    
    store.on("beforeload",function(){
        if (gridisedit){
            saveForm();
        }
    });
    function getDemlist(){
        var sender={};
        var array=[];
        for (var i=0;i<dimLen;i++){
            var o={};
            o.facdimtable = Ext.ComponentMgr.get("facdimtable"+i).getValue();
            o.facdimcodecol = Ext.ComponentMgr.get("facdimcodecol"+i).getValue();
            o.facdimvalue = Ext.ComponentMgr.get("facdimvalue"+i).getValue();
            //demArr[i]  = o;
            array.push(o);
        }
        sender.demlist = array;
      //  alert(Ext.util.JSON.encode(sender));
        return Ext.util.JSON.encode(sender);
    } 

    /**
     * 获取导出数据采集模版筛选的维度
     */
    function getExportDemlist(){
        var sender={};
        var array=[];
        for (var i=0;i<dimLen;i++){
            var o={};
            o.facdimtablewan = Ext.ComponentMgr.get("facdimtablewan"+i).getValue();
            o.facdimcodecolwan = Ext.ComponentMgr.get("facdimcodecolwan"+i).getValue();
            o.facdimvaluewan = Ext.ComponentMgr.get("facdimvaluewan"+i).getValue();
            o.facdimfieldwan=Ext.ComponentMgr.get("facdimfieldwan"+i).getValue();
            o.facdimtable_weidu = Ext.ComponentMgr.get("facdimtable_weidu"+i).getValue();
            o.facdimcodecol_weidu = Ext.ComponentMgr.get("facdimcodecol_weidu"+i).getValue();
            o.facdimvalue_weidu = Ext.ComponentMgr.get("facdimvalue_weidu"+i).getValue();
            //demArr[i]  = o;
            array.push(o);
        }
        sender.demlist = array;
       // alert(Ext.util.JSON.encode(sender));
        return Ext.util.JSON.encode(sender);
    } 
    //主视图
    var viewport = new Ext.Viewport({
        layout : 'border',
        items:[{
            tbar : ['-', {
                text : '维度过滤',
                iconCls :'',
                handler : function() {
                    //                   selectItem();
                    modalwin_f.show();
                    modalwin_f.doLayout();
                }
            }, '-', {
                text : '保存',
                handler : function() {
                    saveForm();
                }
            }, '-', {
                text : '关闭',
                handler : function() {
                    window.close();
                }
            },'-',{
                text:'参照上期模版',
                handler : function() {
                    showSQ();
                }
            },{
                text:'包含值',
                xtype:'label'
            },{
                xtype:'checkbox',
                id:'bhz'
            },'-',{
            	text:'导出数据采集模版',
            	handler:function(){
            	shuju_win.show();
            	shuju_win.doLayout();
            }
            },'-',{
            	text:'用模板导入',
            	handler:function(){
            	win_upload.show();
            }
            },{
                text:'筛选完成值',
                hidden:true,
                xtype:'label'
            },{
                xtype:'checkbox',
                hidden:true,
                id:'zxwcz'
            }
            ],
            region : 'center',
            deferredRender : false,
            frame : true,
            layout : 'border',
            
            items:[
            {
                region : 'center',
                deferredRender : false,
                frame : true,
                layout:'anchor',
                items:[grid]
            }
            ]
        }]

    });     
    //回车换行
    grid.on("afteredit",function(e){
        gridisedit = true;
        if(e.row<grid.getStore().getCount()-1){ 
            var delay = new Ext.util.DelayedTask(function(){
                grid.startEditing(e.row+1,e.column);
            });
            delay.delay(50);
	
        }
    });

    var form = new Ext.form.FormPanel({  
        baseCls : 'x-plain',  
        labelWidth : 70,  
        labelHeight: 150,  
        fileUpload : true,  
        defaultType : 'textfield',  
        items : [{  
           xtype : 'textfield',  
           fieldLabel : '选择文件',  
           name : 'userfile',  
           id : 'userfile',  
           inputType : 'file',  
           anchor : '95%' // anchor width by percentage  
          }]  
      
   });  
    //上传文件的窗口
    var win_upload = new Ext.Window({ 
        title : '上传文件', 
        width :450, 
        height : 180, 
        modal : true, 
        x : 100, 
        y : 50, 
        layout : 'form', 
        autoScroll : true, 
        constrain : true, 
        bodyStyle : 'padding:10px 10px 10px 10px;', 
        items:form, 
        buttons : [{ 
            text : '确认上传', 
          handler : function() { 
           if (form.form.isValid()) { 
            if(Ext.getCmp('userfile').getValue() == ''){ 
             Ext.Msg.alert('提示','请选择要上传的文件'); 
             return; 
            } 
            Ext.MessageBox.show({ 
               title : '请稍后....', 
               msg : '文件正在上传中....', 
               progressText : '', 
               width : 300, 
               progress : true, 
               closable : false, 
               animEl : 'loding' 
            }); 
            form.getForm().submit({ 
                url : basePath+'servlet/Upload', 
                method : 'POST', 
                success : function(form, action) { 
                Ext.Msg.alert('成功','文件上传成功！'); 
                win_upload.hide(); 
                importXls(action.result.url);
             }, 
             failure : function(form, action) { 
                Ext.Msg.alert('错误',"文件上传失败，请重新操作！"); 
             } 
            }) 
           } 
          } 
        }, { 
            text : '关闭', 
            handler : function() { 
                win_upload.hide(); 
        } 
        }], 
        closable: false, 
        draggable: false, 
        resizable: false 
    }); 
  
    function saveForm(){   
        var objInfo = new Object();
        //检查是否编辑，并提示保存
        var store = grid.getStore();  
        //得到修改过的Recored的集合  
        var bhz=Ext.getCmp("bhz").getValue();
        var modified= store.modified.slice(0);
        if(bhz){
            modified=store.getRange(0,store.getTotalCount());
        }else{
            modified  = store.modified.slice(0);  
        }
        if(modified==null || modified=="")
        {
            return;
        }
        
        gridisedit = false;
        //将数据放到另外一个数组中  
        var jsonArray = [];  
        var breturn = false;
        Ext.each(modified,function(m){  
            //m.data中保存的是当前Recored的所有字段的值json，不包含结构信息 
            if (m && m.data){
                var val = m.data.REPVAL;
                if (isDigitzh(val)){
                    breturn = true;
                    alert("只能是数字或者+-符号！");
                    return;
                }
            }
            jsonArray.push(m.data); 
        }); 
        if (breturn) {
            return;
        }
        objInfo.listData = jsonArray;
        var saveItemInfoUrl = "";
        saveItemInfoUrl = '?className=cn.com.jsepc.rep.report.FillDataDAO';
        saveItemInfoUrl += '&methodName=DatatbUpdate';
        saveItemInfoUrl += '&paramCount=2&param_0='+repid+"&param_1="+roleid;
        saveItemInfoUrl = basePath + 'JarpListener' + saveItemInfoUrl;
        httpR_itemInfo = getXMLHttpRequest();
        httpR_itemInfo.onreadystatechange = returnItemUpdate;
        httpR_itemInfo.open("POST", saveItemInfoUrl, true);
        httpR_itemInfo.send(Ext.util.JSON.encode(objInfo));

    }
 
    function returnItemUpdate() {
        if (httpR_itemInfo.readyState == 4) {
            if (httpR_itemInfo.status == 200) { 
                ret = httpR_itemInfo.responseText;
                if (ret=='ok'){
                    alert('数据修改成功！');
                    query();
                }else if (ret=='no'){
                    alert('数据没有修改！');
                }else{
                    alert('数据修改失败！');
                }
            }
        }
    }
    
   

    //点击 参照上期模版 执行
    function showSQ(){
        var bhz=Ext.getCmp("bhz").getValue();
        var zxwcz=Ext.getCmp("zxwcz").getValue();  //筛选完成值
       
        if(zxwcz){
            //判断是否有上期值
            var saveItemInfoUrl = "";
            saveItemInfoUrl = '?className=cn.com.jsepc.rep.report.FillDataSQ_Wan';
            saveItemInfoUrl += '&methodName=hasSQ';
            saveItemInfoUrl += '&paramCount=1&param_0='+repid;
            saveItemInfoUrl = basePath + 'JarpListener' + saveItemInfoUrl;
            httpR_itemInfo = getXMLHttpRequest();
            httpR_itemInfo.onreadystatechange = hasvalue;
            httpR_itemInfo.open("POST", saveItemInfoUrl, true);
            httpR_itemInfo.send();
            function hasvalue(){
                if (httpR_itemInfo.readyState == 4) {
                    if (httpR_itemInfo.status == 200) {
                        ret = httpR_itemInfo.responseText;
                        if (ret == 'ok') {
                                   
                        }else{
                            Ext.MessageBox.alert("错误","没有上期值模板，请去掉参照上期值后并手动筛选维度")
                        }
                    }
                }
            } 
        }else{
            //判断是否有上期值
            var saveItemInfoUrl = "";
            saveItemInfoUrl = '?className=cn.com.jsepc.rep.report.FillDataSQ';
            saveItemInfoUrl += '&methodName=hasSQ';
            saveItemInfoUrl += '&paramCount=1&param_0='+repid;
            saveItemInfoUrl = basePath + 'JarpListener' + saveItemInfoUrl;
            httpR_itemInfo = getXMLHttpRequest();
            httpR_itemInfo.onreadystatechange = hasvalue;
            httpR_itemInfo.open("POST", saveItemInfoUrl, true);
            httpR_itemInfo.send();
            function hasvalue(){
                if (httpR_itemInfo.readyState == 4) {
                    if (httpR_itemInfo.status == 200) {
                        ret = httpR_itemInfo.responseText;
                        if (ret == 'ok') {
                                   
                        }else{
                            Ext.MessageBox.alert("错误","没有上期值模板，请去掉参照上期值后并手动筛选维度")
                        }
                    }
                }
            } 
        
        
            //判断是否有当期值
            var requestHasThis = "";
            requestHasThis = '?className=cn.com.jsepc.rep.report.FillDataSQ';
            requestHasThis += '&methodName=hasThis';
            requestHasThis += '&paramCount=1&param_0='+repid;
            requestHasThis = basePath + 'JarpListener' + requestHasThis;
            httpR_itemInfo = getXMLHttpRequest();
            httpR_itemInfo.onreadystatechange = hasThis;
            httpR_itemInfo.open("POST", requestHasThis, true);
            httpR_itemInfo.send();
            function hasThis(){
                if (httpR_itemInfo.readyState == 4) {
                    if (httpR_itemInfo.status == 200) {
                        ret = httpR_itemInfo.responseText;
                        if (ret == 'ok') {
                                   
                        }else{
                            Ext.MessageBox.alert("错误","维度表数据缺失，请联系维护人员维护相关维度表")
                        }
                    }
                }
            } 
        
        }
        
        if(!zxwcz){
            if(bhz){
                var openUrl = basePath
                + 'JarpListener?className=cn.com.jsepc.rep.report.FillDataSQ';
                openUrl += '&methodName=getGridData&paramCount=5&param_2='+repid+'&param_3='+corpid+'&param_4=true'; 
                hideColumn([]); 
            }else{
                var openUrl = basePath
                + 'JarpListener?className=cn.com.jsepc.rep.report.FillDataSQ';
                openUrl += '&methodName=getGridData&paramCount=5&param_2='+repid+'&param_3='+corpid+'&param_4=false'; 
                hideColumn([]);  
            }
        }else{
            if(bhz){
                var openUrl = basePath
                + 'JarpListener?className=cn.com.jsepc.rep.report.FillDataSQ_Wan';
                openUrl += '&methodName=getDataGrid&paramCount=5&param_2='+repid+'&param_3='+corpid+'&param_4=true'; 
                hideColumn([]); 
            }else{
                var openUrl = basePath
                + 'JarpListener?className=cn.com.jsepc.rep.report.FillDataSQ_Wan';
                openUrl += '&methodName=getDataGrid&paramCount=5&param_2='+repid+'&param_3='+corpid+'&param_4=false'; 
                hideColumn([]);  
            }
        }
       
        store.proxy = new Ext.data.HttpProxy( {
            url : openUrl
        });
        store.load({
            params : {
                param_0:0,
                param_1:pagesize
            }
        });
        
    }

    //查询
    function selectItem(){       
        if (gridisedit){
            saveForm();
        }else{
            var iswcz=Ext.getCmp("iswcz").getValue();  //完成值
            //未勾选完成值
            if(!iswcz){
                var openUrl = basePath
                + 'JarpListener?className=cn.com.jsepc.rep.report.FillDataDAO';
                openUrl += '&methodName=getDataGrid&paramCount=5&param_2='+repid+'&param_3='+corpid+'&param_4='+getDemlist(); 
                hideColumn([]); 
                
            }else{//勾选完成值
                var hideCol=[];
                var array=[];
                var sender={};
                for (var i=0;i<dimLen;i++){
                    var o={};
                    o.facdimtable = Ext.ComponentMgr.get("facdimtable"+i).getValue();
                    o.facdimcodecol = Ext.ComponentMgr.get("facdimcodecol"+i).getValue();
                    o.facdimvalue = Ext.ComponentMgr.get("facdimvalue"+i).getValue();
                    o.facdimfield=Ext.ComponentMgr.get("facdimfield"+i).getValue();
                    if(o.facdimvalue==""){
                        o.facdimvalue="99999";
                        hideCol.push(o.facdimfield);
                    }
                    array.push(o);
                }
                sender.demlist = array;
                sender.iswcz=Ext.getCmp("iswcz").getValue();
			
                //如果勾选完成值，又一个维度都没有勾选，给出提示
                if(hideCol.length==dimLen){
                    Ext.MessageBox.alert("错误提示","请至少选择一个维度过滤条件。");
                    return;
                }
                hideColumn(hideCol);
                var openUrl = basePath
                + 'JarpListener?className=cn.com.jsepc.rep.report.FillDataDao_Wan';
                openUrl += '&methodName=getDataGrid&paramCount=5&param_2='+repid+'&param_3='+corpid+'&param_4='+Ext.util.JSON.encode(sender);
            }
            store.proxy = new Ext.data.HttpProxy( {
                url : openUrl
            });
            store.load({
                params : {
                    param_0:0,
                    param_1:pagesize
                }
            });
        }

    }
    
    /**
     * 导出数据采集模版
     */
    function selectItem_shuju(){
    	var openUrl = basePath
	    + '/servlet/ExportServlet?iswcz=false&';
	    openUrl += 'repid='+repid+'&corpid='+corpid+'&getDemlist='+getExportDemlist()+"&shuju=1"; 
	      window.open(openUrl);
    }


    //设置列隐藏
    function hideColumn(hiddenCols){
        var columnModel=grid.getColumnModel();
        for(var i=0;i<columnModel.getColumnCount();i++){
            var dataIndex=columnModel.getDataIndex(i);
            var flag=false;
            for(var j=0;j<hiddenCols.length;j++){
                if(dataIndex.indexOf(hiddenCols[j])>=0){
                    flag=true;
                    break;
                }
            }
            //如果需要隐藏的列
            if(flag){
                columnModel.setHidden(i,true);
            }else{
                var header=columnModel.getColumnHeader(i);
                if(header.indexOf("ID")>=0){
                    columnModel.setHidden(i,true);
                }else{
                    columnModel.setHidden(i,false);
                }
            }
        }
    }

    //查询
    function query(){       
        store.commitChanges();
    }

    //判断字符串不能以数字开头
    function isDigitzh(s) 
    { 
        var patrn=/^[0-9-.]{0,32}$/; 
        if (patrn.exec(s)){
            return false; 
        }else{
            return true;
        }
    }
    //导入excel
    function importXls(url){
    	var openUrl = basePath
        + 'JarpListener?className=cn.com.jsepc.rep.report.ImportXls';
        openUrl += '&methodName=AdminOperate&paramCount=3&param_0='+url+'&param_1='+repid+'&param_2='+roleid;
        httpR_itemInfo = getXMLHttpRequest();
        httpR_itemInfo.onreadystatechange = resultXls;
        httpR_itemInfo.open("POST", openUrl, true);
        httpR_itemInfo.send();
    }
    
    function resultXls(){
    	if (httpR_itemInfo.readyState == 4) {
            if (httpR_itemInfo.status == 200) {
                ret = httpR_itemInfo.responseText;
                alert(ret);
            }
        }
    }
});